/* Copyright 203-2115 AtomWare Technology Pty Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * The flowing information must be keep 
 * GroupBy.java
 * wholebasic
 * 2013-6-18上午9:47:54
 * @author 屈甲康
 * QQ285799123
 * mailto:qujiakang@gmail.com
 */

package org.jackysoft.query;

import java.util.Collection;
import java.util.List;
import java.util.ListIterator;

import org.apache.commons.lang.StringUtils;
import org.springframework.util.CollectionUtils;

import com.google.common.collect.Lists;
/**
 * query aider to help collect 
 * sql group by condition
 * @see Order
 * 
 * **/
public class GroupBy extends Aggregation{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -8658457757411177168L;
	protected List<QueryField> havings = Lists.newArrayList();
	private List<Aggregation> names = Lists.newArrayList();
	
	public GroupBy() {
		super();	
	}

	
	
	public List<QueryField> getHavings() {
		return havings;
	}

	public void setHavings(List<QueryField> havings) {
		this.havings = havings;
	}
	
	
	public List<Aggregation> getNames() {
		return names;
	}


	public void setNames(List<Aggregation> names) {
		this.names = names;
	}
	
	public String groupString(){
		Collection<String> gstr = Lists.newArrayList();
		for(Aggregation name:names){
		    gstr.add(name.aggregate(null));	
		}		
		
		if(gstr.isEmpty()) return "";
		
		return " group by "+StringUtils.join(gstr, ',')+ this.havingString();
	   
	}
	
	protected String havingString(){
		
		if(CollectionUtils.isEmpty(havings))return "";
		
		String qs = "";
		org.jackysoft.util.CollectionUtils.filter(havings, new EmptyQueryFieldPredicate());
		ListIterator<QueryField> litr = havings.listIterator();
		
	    int size = havings.size();
		for(;litr.hasNext();){
		   QueryField qf = litr.next();
		   if(qf==null)continue;		   
		   int nidx = litr.nextIndex();
		   if(nidx  == size){
			   qf.setNoOutOpr(true);
		   }		   
		   qs+=qf;
		}  
		if(StringUtils.isBlank(qs)) return "";
		return " having "+qs;
	}

}
